package com.doge.calcalbum.api

import androidx.lifecycle.LifecycleOwner
import com.doge.calcalbum.R
import com.doge.calcalbum.utils.toast
import io.reactivex.observers.DisposableObserver
import java.net.SocketTimeoutException
import java.net.UnknownServiceException

open class ObserverAdapter<T>(owner: LifecycleOwner? = null) : DisposableObserver<T>() {
    init {
        bindLifecycle(owner)
    }

    override fun onComplete() {
    }

    override fun onNext(t: T) {
    }

    override fun onError(e: Throwable) {
        if (e is ServerException) {
            if (e.msg.isNotEmpty()) {
                toast(e.msg)
            }
        } else if (
            e is retrofit2.adapter.rxjava2.HttpException ||
            e is retrofit2.HttpException
        ) {
            e.printStackTrace()
            if (e.message?.isNotEmpty() == true) {
                toast(e.message.toString())
            }
        } else if (e is SocketTimeoutException) {
            e.printStackTrace()
            toast(R.string.request_timeout)
        } else if (e is java.net.UnknownHostException || e is UnknownServiceException) {
            e.printStackTrace()
            toast(R.string.unable_to_connect_to_server)
        }
    }
}


